/**
 * 是否为空
 * @author hapday
 */
var isEmpty = function(str){
	if(undefined !== str && null !== str && "" !== $.trim(str)){
		return false;
	} else {
		return true;
	}
}

/**
 * 是否为不为空
 * @author hapday
 */
var isNotEmpty = function(str){
	if(undefined === str || null === str || "" === $.trim(str)){
		return false;
	} else {
		return true;
	}
}

//Top link function
jQuery.fn.topLink = function(settings) {
	settings = jQuery.extend({
		min: 1,
		fadeSpeed: 200
	}, settings);
	
	return this.each(function() {
		//listen for scroll
		var el = $(this);
		el.hide(); //in case the user forgot
		$(window).scroll(function() {
			if($(window).scrollTop() >= settings.min)
			{
				el.fadeIn(settings.fadeSpeed);
			}
			else
			{
				el.fadeOut(settings.fadeSpeed);
			}
		});
	});
};

//set the link
$('.top-scroll').topLink({
	min: 200,
	fadeSpeed: 500
});

//smooth scroll
$('.top-scroll').click(function(e) {
	e.preventDefault();
	$.scrollTo(0,700);
});

/*function smoothLink() {

	// Smooth scroll
    $('.scroll-link').bind('click.smoothscroll',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        if($target.offset() == undefined) return;

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-110
        }, 900, 'swing', function () {
            if($('body').hasClass('auto-close-menu') && $('.menu-open').length > 0){
                $('#menuToggle, #menuToggleLeft').click();
            }
            
        });
    });

    $('.scroll-link').click(function (e) {
    	$('#review').trigger('click');
    });
}*/
//end function

//Start function
/*function smoothScrollInit() {

		// Smooth scroll
    $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        if($target.offset() == undefined) return;

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-110
        }, 900, 'swing', function () {
            if($('body').hasClass('auto-close-menu') && $('.menu-open').length > 0){
                $('#menuToggle, #menuToggleLeft').click();
            }
            
        });
    });
}*/
//end function





/**
 * 将数字金额转为大写
 */
function digit_uppercase(n) {
	var fraction = [ '角', '分' ];
	var digit = [ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' ];
	var unit = [ [ '元', '万', '亿' ], [ '', '拾', '佰', '仟' ] ];
	var head = n < 0 ? '欠' : '';
	n = Math.abs(n);
	var s = '';
	for (var i = 0; i < fraction.length; i++) {
		s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i])
				.replace(/零./, '');
	}
	s = s || '整';
	n = Math.floor(n);
	for (var i = 0; i < unit[0].length && n > 0; i++) {
		var p = '';
		for (var j = 0; j < unit[1].length && n > 0; j++) {
			p = digit[n % 10] + unit[1][j] + p;
			n = Math.floor(n / 10);
		}
		s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
	}
	return head
			+ s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/,
					'零元整');
}

/**
 * 载入导航轨迹
 */
function loadNavigation() {
	var cookie_nav = $.cookie(cookieName_navigation);
	if (cookie_nav) {
		$('#left_nav').find('.load-content').each(function() {
			if ($(this).attr('hid') == cookie_nav) {
				$(this).parent().addClass('active');
				$(this).parent().parent().show();
				$(this).parent().parent().parent().addClass('active');
			}
		});
	}
}

/**
 * 更新导航轨迹
 */
function updateNavigation(hid) {
	if (hid) {
		$.cookie(cookieName_navigation, hid, {
			expires : 36000000,
			path : '/'
		});
	}
}

/**
 * Ajax 加载页面 - 适用于局部，或者使用 js 进行页面跳转
 */
function loadingAjax(href, obj) {
	if (href != '' && href != '#' && href != './') {
		if (!obj) {
			obj = $("#content");
		}
		obj.load(href, function() {
			history.pushState({}, null, href);
		});
	}
}

/**
 * 提示信息处理，可定时清除
 * 
 * @param string
 *            obj_id 提示信息对象 ID
 * @param string
 *            msg 提示信息内容
 * @param boolean
 *            clear 是否自动清除
 * @param integer
 *            delayTime 延迟时间
 */
function notice(obj_id, msg, clear, delayTime) {
	$("#" + obj_id).html(msg);
	if (clear) {
		if (!delayTime) {
			delayTime = 5000;
		}
		setTimeout(function() {
			$("#" + obj_id).empty();
		}, delayTime);
	}
}

/**
 * 消息通知 - pnotify
 * 
 * @param string
 *            $msg 必填。提示信息
 * @param string
 *            $type 选填。提示类型，一共四种：warning、info、success、error
 * @param string
 *            $title 选填。提示标题
 */
function pnotify($msg, $type, $title) {
	new PNotify({
		title : $title ? $title : '提醒',
		text : $msg,
		type : $type ? $type : 'warning',
		styling : 'bootstrap3',
	});
}

/**
 * 更新 CKEDITOR 的状态，即值 适用版本：4.0以上
 */
function CKupdate() {
	for (instance in CKEDITOR.instances)
		CKEDITOR.instances[instance].updateElement();
}

/**
 * 判断 js 数组包是否包含某个元素，类似 PHP 的数组函数 in_array() 使用方法： var arr = ["a","b"];
 * alert(arr.in_array("a"));
 */
Array.prototype.S = String.fromCharCode(2);
Array.prototype.in_array = function(e) {
	var r = new RegExp(this.S + e + this.S);
	return (r.test(this.S + this.join(this.S) + this.S));
}

/**
 * ajaxError
 */
function ajaxError(XMLHttpRequest, textStatus, errorThrown) {
	alert('Ooops!Encountered error while connecting to the server.There might be something wrong with your network.Please check your network connection!');
	$('#edit_notice').empty();
	$(".input-submit").removeAttr('disabled');
}

function compareDatStr(begin, end) {
	var begin = getDateFromStr(begin);
	var end = getDateFromStr(end);
	if (begin.getTime() > end.getTime()) {
		return false;
	}
	return true;
}

function getDateFromStr(dateStr) {
	return new Date(dateStr.replace(/-/g, "/"));
}

/**
 * 转换日期格式，将秒型日期转换为yyyy-MM-dd格式的日期
 * 
 * @param milliSecond
 *            java后台传来的秒型日期
 */
function getDate(milliSecond) {
	if (milliSecond != null && milliSecond != "") {
		return new Date(milliSecond).Format("yyyy-MM-dd");
	} else {
		return "";
	}
}

function getDateTime(milliSecond) {
	if (milliSecond != null && milliSecond != "") {
		return new Date(milliSecond).Format("yyyy-MM-dd hh:mm:ss");
	} else {
		""
	}
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) { // author: meizz
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

// ///////////////////// 预览本地图片 - start /////////////////////
/**
 * js本地图片预览，兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
 * 
 * @param fileObject
 * @param previewImageId
 * @param imagePreview_div
 */
function previewImage(fileObject, previewImageId, imagePreview_div) {
	var allowExtention = ".jpg,jpeg,.bmp,.gif,.png";// 允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
	var extention = fileObject.value.substring(
			fileObject.value.lastIndexOf(".") + 1).toLowerCase();
	var browserVersion = window.navigator.userAgent.toUpperCase();
	if (allowExtention.indexOf(extention) > -1) {
		if (fileObject.files) {// HTML5实现预览，兼容chrome、火狐7+等
			if (window.FileReader) {
				var reader = new FileReader();
				reader.onload = function(e) {
					document.getElementById(previewImageId).setAttribute("src",
							e.target.result);
				}
				reader.readAsDataURL(fileObject.files[0]);
			} else if (browserVersion.indexOf("SAFARI") > -1) {
				alert("不支持Safari6.0以下浏览器的图片预览!");
			}
		} else if (browserVersion.indexOf("MSIE") > -1) {
			if (browserVersion.indexOf("MSIE 6") > -1) {// ie6
				document.getElementById(previewImageId).setAttribute("src",
						fileObject.value);
			} else {// ie[7-9]
				fileObject.select();
				if (browserVersion.indexOf("MSIE 9") > -1)
					fileObject.blur();// 不加上document.selection.createRange().text在ie9会拒绝访问
				var newPreview = document.getElementById(imagePreview_div
						+ "New");
				if (newPreview == null) {
					newPreview = document.createElement("div");
					newPreview.setAttribute("id", imagePreview_div + "New");
					newPreview.style.width = document
							.getElementById(previewImageId).width
							+ "px";
					newPreview.style.height = document
							.getElementById(previewImageId).height
							+ "px";
					newPreview.style.border = "solid 1px #d2e2e2";
				}
				newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='"
						+ document.selection.createRange().text + "')";
				var tempDivPreview = document.getElementById(imagePreview_div);
				tempDivPreview.parentNode.insertBefore(newPreview,
						tempDivPreview);
				tempDivPreview.style.display = "none";
			}
		} else if (browserVersion.indexOf("FIREFOX") > -1) {// firefox
			var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(
					/firefox\/([\d.]+)/)[1]);
			if (firefoxVersion < 7) {// firefox7以下版本
				document.getElementById(previewImageId).setAttribute("src",
						fileObject.files[0].getAsDataURL());
			} else {// firefox7.0+
				document.getElementById(previewImageId).setAttribute("src",
						window.URL.createObjectURL(fileObject.files[0]));
			}
		} else {
			document.getElementById(previewImageId).setAttribute("src",
					fileObject.value);
		}
	} else {
		alert("仅支持" + allowExtention + "为后缀名的文件!");
		fileObject.value = "";// 清空选中文件
		if (browserVersion.indexOf("MSIE") > -1) {
			fileObject.select();
			document.selection.clear();
		}
		fileObject.outerHTML = fileObject.outerHTML;
	}
}




function previewImage2(fileObject, previewImageId, imagePreview_div) {
	var allowExtention = ".mp3,.mp4,.wav";// 允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
	var extention = fileObject.value.substring(
			fileObject.value.lastIndexOf(".") + 1).toLowerCase();
	var browserVersion = window.navigator.userAgent.toUpperCase();
	if (allowExtention.indexOf(extention) > -1) {
		if (fileObject.files) {// HTML5实现预览，兼容chrome、火狐7+等
			if (window.FileReader) {
				var reader = new FileReader();
				reader.onload = function(e) {
					document.getElementById(previewImageId).setAttribute("src",
							e.target.result);
				}
				reader.readAsDataURL(fileObject.files[0]);
			} else if (browserVersion.indexOf("SAFARI") > -1) {
				alert("不支持Safari6.0以下浏览器的图片预览!");
			}
		} else if (browserVersion.indexOf("MSIE") > -1) {
			if (browserVersion.indexOf("MSIE 6") > -1) {// ie6
				document.getElementById(previewImageId).setAttribute("src",
						fileObject.value);
			} else {// ie[7-9]
				fileObject.select();
				if (browserVersion.indexOf("MSIE 9") > -1)
					fileObject.blur();// 不加上document.selection.createRange().text在ie9会拒绝访问
				var newPreview = document.getElementById(imagePreview_div
						+ "New");
				if (newPreview == null) {
					newPreview = document.createElement("div");
					newPreview.setAttribute("id", imagePreview_div + "New");
					newPreview.style.width = document
							.getElementById(previewImageId).width
							+ "px";
					newPreview.style.height = document
							.getElementById(previewImageId).height
							+ "px";
					newPreview.style.border = "solid 1px #d2e2e2";
				}
				newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='"
						+ document.selection.createRange().text + "')";
				var tempDivPreview = document.getElementById(imagePreview_div);
				tempDivPreview.parentNode.insertBefore(newPreview,
						tempDivPreview);
				tempDivPreview.style.display = "none";
			}
		} else if (browserVersion.indexOf("FIREFOX") > -1) {// firefox
			var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(
					/firefox\/([\d.]+)/)[1]);
			if (firefoxVersion < 7) {// firefox7以下版本
				document.getElementById(previewImageId).setAttribute("src",
						fileObject.files[0].getAsDataURL());
			} else {// firefox7.0+
				document.getElementById(previewImageId).setAttribute("src",
						window.URL.createObjectURL(fileObject.files[0]));
			}
		} else {
			document.getElementById(previewImageId).setAttribute("src",
					fileObject.value);
		}
	} else {
		alert("仅支持" + allowExtention + "为后缀名的文件!");
		fileObject.value = "";// 清空选中文件
		if (browserVersion.indexOf("MSIE") > -1) {
			fileObject.select();
			document.selection.clear();
		}
		fileObject.outerHTML = fileObject.outerHTML;
	}
}
// ///////////////////// 预览本地图片 - end /////////////////////


/**
 * 只能是数字
 */
var onlyNumber = function() {
	if (!(event.keyCode == 46) && !(event.keyCode == 8)
			&& !(event.keyCode == 37) && !(event.keyCode == 39))
		if (!((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)))
			event.returnValue = false;
}

/*function IsNum(num){
	  var reNum=/^\d*$/;
	  return(reNum.test(num));
	}*/

/**
 * 身份证号是否合法
 */
var isIdentityNumber = function(identityNumber){
	if(isEmpty(identityNumber)){
		return false;
	} else {
		identityNumber = identityNumber.toUpperCase();
		
		if (/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(identityNumber)){
			return true;
		} else {
			return false;
		}
	}
}

/**
 * 时间验证器
 */
var timeValidator = function(time) {
	if (isEmpty(time)) {
		return false;
	}

	var reg = /^([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
	if (reg.test(time)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 尖括号、引号、&、替换为响应的 XML 标识
 */
var specificSymbolToTxt = function(str) {
	var RexStr = /\<|\>|\"|\'|\&/g
	str = str.replace(RexStr, function(MatchStr) {
		switch (MatchStr) {
		case "<":
			return "&lt;";
			break;
		case ">":
			return "&gt;";
			break;
		case "\"":
			return "&quot;";
			break;
		case "'":
			return "&#39;";
			break;
		case "&":
			return "&amp;";
			break;
		default:
			break;
		}
	})
	return str;
}

/**
 * 双引号替换为空字符
 */
var doubleQuotationMarksReplaceBlank = function(object) {
	// var reg = /^[^\%\'\"\?]*$/;
	// var reg = /^[^"]*$/g;
	var reg = /^\"|\"$/g;

	// var str='数据库取出的正则表达式';
	// str.replace(/^\"|\"$/g,'');

	if (reg.test(object.value)) {
		object.value = '';

		return;
	}
}

/**
 * 获取 URL 参数数组
 */
function getUrlParams() {
	var href = window.location.href;
	
	if(undefined === href || null === href || "" === $.trim(href)){
		return;
	}
	
	var questionMarkIndex = href.indexOf("?");
//	var wellMarkIndex = href.indexOf("#");
	
	// 无参数
	if(-1 === questionMarkIndex){
		return null;
	} 
	
	var source = "";
	/*if(-1 !== wellMarkIndex){
		source = href.substring(questionMarkIndex + 1, wellMarkIndex);
	} else {
		source = href.substring(questionMarkIndex + 1, href.length);
	}*/
	source = href.substring(questionMarkIndex + 1, href.length);
	
	if(undefined === source || null === source || "" === $.trim(source)){
		return "";
	}

	var params = source.split("&");

	// 无参数
	if(undefined === params || null === params || "" === $.trim(params)){
		return "";
	}
	
	return params;
}

/**
 * 获取 URL 参数 JSON
 */
function getUrlParamJson() {
	var href = window.location.href;
	
	if(undefined === href || null === href || "" === $.trim(href)){
		return;
	}
	
	var questionMarkIndex = href.indexOf("?");
//	var wellMarkIndex = href.indexOf("#");
	
	if(-1 === questionMarkIndex){
		return null;
	} 
	
	var source = "";
	/*if(-1 !== wellMarkIndex){
		source = href.substring(questionMarkIndex + 1, wellMarkIndex);
	} else {
		source = href.substring(questionMarkIndex + 1, href.length);
	}*/
	source = href.substring(questionMarkIndex + 1, href.length);
	
	if(undefined === source || null === source || "" === $.trim(source)){
		return "";
	}

	var params = source.split("&");

	if(undefined === params || null === params || "" === $.trim(params)){
		return "";
	}
	
	var paramJSON = "{";
	
	for(var index = 0; index < params.length; index++){
		var param = params[index];
		
		if(undefined === params || null === params || "" === $.trim(params)){
			continue;
		}
		
		var items = param.split("=");
		
		var key = items[0];
		var value = items[1];
		
		paramJSON += key + ":'" + value + "',";
	}
	
	if(1 < paramJSON.length){
		paramJSON = paramJSON.substring(0, paramJSON.length - 1);
	}
	
	paramJSON += "}";
	
	return eval("(" + paramJSON + ")");
}

/**
 * 获取 restful 风格的参数数组
 */
/*var getUrlRestfulParameters = function (separator) {
	var href = window.location.href;
	
	if(isEmpty(href)){
		return null;
	}
	
	if(isEmpty(separator)){
		separator = '/';
	}
	
	var separatorIndex = href.lastIndexOf(separator);
	
	if(-1 === separatorIndex){
		return null;
	} 
	
	var source = href.substring(separatorIndex + 1, href.length);
	
	if(isEmpty(source)){
		return null;
	}
	
	var params = source.split('/');

	return params;
}*/

/**
 * 获取 restful 风格的参数数组
 */
var getRestfulParameters = function (separator) {
	var pathname = window.location.pathname;
	
	if(isEmpty(pathname)){
		return null;
	}
	
	if(isEmpty(separator)){
		separator = '/';
	}
	
	if(isEmpty(pathname)){
		return null;
	}
	
	var params = pathname.substring(1, pathname.length).split('/');
	
	return params;
}

/**
 * 是否是正数（可以含两位小数）
 */
var isFinanceNumber = function(object, message){
	var exp = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/g;
	
	if(!exp.test(object.value)){
//		object.value = 0.0;
//		object.focus();
		
		if(isNotEmpty(message)){
			layer.msg(message);
		}
		
		return false;
	}
	
	return true;
}

/**
 * 清空表单
 */
var clearForm = function(formId){
	$(':input', '#' + formId + '').not(':button, :submit, :reset, :hidden, :radio').val('').removeAttr('checked').removeAttr('selected');
}

/**
 * 清空表单
 */
var clearForm2 = function(formId){
	$('#' + formId + '')[0].reset();
}

/**
 * 日期比较
 * startDate 起始日期
 * endDate 截止日期
 */
var dateCompare = function(startDate, endDate){
	if(isEmpty(startDate)){
		layer.msg('起始日期不可为空！');
		
		return false;
	}
	if(isEmpty(endDate)){
		layer.msg('截止日期不可为空！');
		
		return false;
	}
	
	var todayDate = new Date();
	var currentYear = todayDate.getFullYear();
	var currentMonth = todayDate.getMonth() + 1;
	var currentDate = todayDate.getDate();
	
	if(10 > currentMonth){
		currentMonth = '0' + currentMonth;
	}
	
	var todayDateTemp = new Date(currentYear + '/' + currentMonth + '/' + currentDate);
	var startDateTemp = new Date(startDate.replace(/-/g, '/') + " 00:00:01");
	var endDateTemp = new Date(endDate.replace(/-/g, '/') + " 23:23:59");
	
	if(startDateTemp < todayDateTemp){
		layer.msg('【起始日期】不可早于【今天】！');
		
		return false;
	}
	if(startDateTemp >= endDateTemp){
		layer.msg('【起始日期】不可晚于【截止日期】！');
		
		return false;
	}
	
	return true;
}

/**
 * 时间比较
 * startTime 起始时间
 * endTime 截止时间
 */
var timeCompare = function(startTime, endTime){
	if(isEmpty(startTime)){
		layer.msg('起始时间不可为空！');
		
		return false;
	}
	if(isEmpty(endTime)){
		layer.msg('截止时间不可为空！');
		
		return false;
	}
	
	startTime = '1970/01/01 ' + startTime + ':00';
	endTime = '1970/01/01 ' + endTime + ':00';
	
	var startTimeTemp = new Date(startTime);
	var endTimeTemp = new Date(endTime);
	
	if(startTimeTemp >= endTimeTemp){
		layer.msg('【起始时间】必须早于【截止时间】！');
		
		return false;
	}
	
	return true;
}

/**
 * 获取当前日期
 * 2016-10-27
 * hapday
 */
var getCurrentDate = function() {
	var nowDate = new Date();
	
	return nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate();
}

/**
 * 日期格式化
 */
var dateFormat = function(sourceDate)   { 
	if(isEmpty(sourceDate)) {
		return '';
	}
	
    var year = sourceDate.getFullYear();
    var month = sourceDate.getMonth() + 1;
    var date = sourceDate.getDate();     
    var hour = sourceDate.getHours();     
    var minute = sourceDate.getMinutes();     
    var second = sourceDate.getSeconds();  
    
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;     
}

/**
 * 日期格式化
 */
var dateFormat2 = function(sourceDate)   { 
	if(isEmpty(sourceDate)) {
		return '';
	}
	
	var year = sourceDate.year + 1900;
	var month = sourceDate.month + 1;
	var date = sourceDate.date;     
	var hour = sourceDate.hours;     
	var minute = sourceDate.minutes;     
	var second = sourceDate.seconds;  
	
	return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;     
}

/**
 * 时间戳转本地化时间
 */
var timestampToLocalTime = function(timestamp){
	var date = new Date(timestamp)
	
	return dateFormat(date);
}

var deleteHtmlTag = function(str) {
	return str.replace(/<[^>]+>/g, "");//去掉所有的html标记
}

function removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str=str.replace(/ /ig,'');//去掉 
    return str;
}

/**
 * 获取会话ID
 * @returns
 */
function getSessionId() {
	var c_name = 'JSESSIONID';
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=")
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1
			c_end = document.cookie.indexOf(";", c_start)
			if (c_end == -1)
				c_end = document.cookie.length
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
}

/**
 * 会话已过期
 * */
var sessionValid = function(){
//	layer.msg('已退出', { icon : 16, time: 2000, shade : 0.09 });
	setTimeout(function(){
		window.location.href = host + "signin.html";
	}, 1000);
}

/**
 * 设置 AJAX 全局参数
 * */
$.ajaxSetup({  
    cache		: 	false, 	// close AJAX cache  
    contentType	:	"application/x-www-form-urlencoded;charset=utf-8",   
    complete	:	function(XHR, textStatus){     
        var result = XHR.responseJSON;  
        
        if(undefined !== result && null !== result && "" !== $.trim(result)){
        	if(4 === result.status){
        		sessionValid();
        		
        		return;
        	}
        }
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
		alert("textStatus = " + textStatus + ", XMLHttpRequest.status = " + XMLHttpRequest.status + ", XMLHttpRequest.readyState = " + XMLHttpRequest.readyState);
	}
});

/**
 * 获取已登录【会员】的信息
 */
var getSignedMember = function(){
	var memberStr = window.sessionStorage.getItem('memberStr');
	
	if(undefined === memberStr || null === memberStr || 0 === memberStr.trim().length) {
		return null;
	}
	
	var member = JSON.parse(memberStr);
	
	return member;
}

$('#signout_navigation_link').click(function(){
	$.ajax({
		url : basePath + 'signout',
		type : "get",
		dataType : "json",
//		data : $('#login_form').serialize(),
		cache : false,
		async : false,
		success : function(data, textStatus, jqXHR) {
			if ('success' == textStatus) {
				if(1 != data.status) {
//					debugger;
//					icon: 5 哭泣，icon: 6 笑脸
					layer.msg(data.message, { time: 2000, icon: 5 });
					
					return;
				}

				window.sessionStorage.setItem('memberStr', '');
				window.location.href = 'signin.html';
			}
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
//			layer.msg("textStatus = " + textStatus + ", XMLHttpRequest.status = " + XMLHttpRequest.status + ", XMLHttpRequest.readyState = " + XMLHttpRequest.readyState);
		}
	});
});

/**
 * 初始化导入【JavaScript】的【引用头】
 */
var initScript = function(){
	$('script').each(function(index, script){
//		console.log(script.src);
//		console.log(script.src.indexOf('http'));
		if(null !== script.src && '' !== script.src && -1 === script.src.indexOf('http')) {
			script.src = host + script.src;
		}
	});
}

/**
 * 写随笔
 */
var writeArticle = function(){
	if( null === getSignedMember() ) {
		layer.msg('您尚未登录，请先登录！', { time: 2000, icon: 5 });
		
		setTimeout(function(){
			window.location.href = host + 'signin';
		}, 2000);
	} else {
		window.location.href = host + 'writeArticle';
	}
}